package indi.kider.server.woniubus.api;

import com.alibaba.fastjson.JSONObject;
import indi.kider.common.model.employee.Employee;
import indi.kider.server.woniubus.service.CommunityInitService;
import indi.kider.server.woniubus.service.related.AuthcService;
import indi.kider.server.woniubus.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pers.vankid.common.model.base.CommonResponse;
import pers.vankid.common.utils.download.FileDownUtil;

import java.io.*;

/**
 * 公寓初始化导入
 */
@RestController
@RequestMapping(value = "communityInit")
public class CommunityInitController {

    @Autowired
    private CommunityInitService communityInitService;
    @Autowired
    private AuthcService authcService;


    /**
     * @api {POST} woniubus/communityInit/exportExcelModel
     * @apiGroup apartment
     * @apiDescription 模板导出
     * @apiParamExample 请求样例：
     * http://localhost:9002/woniubus/communityInit/exportExcelModel
     * @apiSuccessExample {json} 返回样例:
     * {name：'muban.xml'}
     **/
    @PostMapping(value = "exportExcelModel")
    public ResponseEntity<InputStreamResource> exportExcelModel(@RequestBody JSONObject json) throws IOException {
        String fileName = json.getString("fileName");
//        File file = ResourceUtils.getFile("classpath:excelFile/muban.xlsx");
//        return FileDownUtil.downloadFile(FileUtil.file2byte(file), fileName);
          InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("excelFile/muban.xlsx");
          return FileDownUtil.downloadFile(input2byte(inputStream), fileName);
    }

    public static final byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }


    @RequestMapping(value = "importExcelHouseTenant", method = RequestMethod.POST)
    public CommonResponse importExcelHouseTenant(@RequestParam(value="file")MultipartFile file, Long communityId){
        try {
            Employee employee = authcService.getCurrentUser().getData();
            communityInitService.importExcelHouseTenant(file, communityId,employee);
            return CommonResponse.buildAddSuccessResponse("");
        }catch (Exception e){
            return CommonResponse.buildExceptionResponse(e);
        }
    }
}
